﻿using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Reflection;

namespace WinForWebApi
{
    public static class WinControlExtensions
    {
        public static void InitDataGridColumns<T>(this DataGridView dataGridView)
        {
            dataGridView.Columns.Clear();
            Type type = typeof(T);

            foreach(MemberInfo member in type.GetMembers(BindingFlags.Public | BindingFlags.Instance))
            {
                var columnAttr = member.GetCustomAttribute<ColumnAttribute>();
                
                if (columnAttr == null) continue;

                var displayAttr = member.GetCustomAttribute<DisplayAttribute>();
                var columnHeaderText = string.IsNullOrEmpty(displayAttr.Name ) ? member.Name : displayAttr.Name;
                DataGridViewColumn dataGridViewColumn = new DataGridViewColumn();
                dataGridViewColumn.DataPropertyName = member.Name;
                dataGridViewColumn.HeaderText = columnHeaderText;
                dataGridViewColumn.CellTemplate = new DataGridViewTextBoxCell();
                dataGridView.Columns.Add(dataGridViewColumn);

                if (member.MemberType == MemberTypes.Field)
                {
                    var field = member as FieldInfo;
                    dataGridViewColumn.ValueType = field.FieldType;
                }
                if (member.MemberType == MemberTypes.Property)
                {
                    var property = member as PropertyInfo;
                    dataGridViewColumn.ValueType = property.PropertyType;
                }
            }
        }
    }
}
